package edu.biwu.schema.json;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import edu.biwu.Student;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * FastJSON实现JSON和Java对象的互转
 */
public class JSONTest02 {
    @Test
    public void testObjectToJson(){
        Student student = new Student(20131210, "杨过", "男", 25);
        System.out.println(JSON.toJSONString(student));
    }

    @Test
    public void testJsonToObject(){
        String jsonStr = "{\"age\":25,\"gender\":\"男\",\"name\":\"杨过\",\"sno\":20131210}";
        Student student = JSON.parseObject(jsonStr, Student.class);
        System.out.println(student);
    }

    @Test
    public void testListToJson(){
        List<Student> students = Arrays.asList(
                new Student(20131210, "杨过", "男", 25),
                new Student(20130209, "小龙女", "女", 20)
        );
        System.out.println(JSON.toJSONString(students));
        System.out.println(JSON.toJSONString(students, JSONWriter.Feature.PrettyFormat));
    }

    @Test
    public void testJsonToList(){
        String jsonStr = "[{\"sno\":20131210,\"name\":\"杨过\",\"gender\":\"男\",\"age\":25},{\"sno\":20130209,\"name\":\"小龙女\",\"gender\":\"女\",\"age\":20}]";
        JSON.parseArray(jsonStr,Student.class).forEach(System.out::println);
    }

    @Test
    public void testMapToJson(){
        List<Student> students = Arrays.asList(
                new Student(20131210, "杨过", "男", 25),
                new Student(20130209, "小龙女", "女", 20)
        );
        Map<String, Student> map = students.stream().collect(Collectors.toMap(stu -> stu.getSno() + " ", stu -> stu));
        System.out.println(JSON.toJSONString(map));
        JSON.toJSONString(map,JSONWriter.Feature.PrettyFormat);
    }
}
